import { getFilterSelector } from '../utils/cssSelector';
import { isEmptyObject } from '../utils';
import { ContentTypeEnum, IColumn, RowSelectionTypeEnum } from './types';
import { DefaultOnRowScript, InputIds, OutputIds, SlotIds } from './constants';
import { Schemas, upgradeSchema } from './schema';
import {
  OutputIds as PaginatorOutputIds,
  InputIds as PaginatorInputIds
} from './components/Paginator/constants';
import { Data } from './types';
import { addFilterIO } from './editors/table-item/filterEditor';

export default function ({
  data,
  setDeclaredStyle,
  getDeclaredStyle,
  removeDeclaredStyle,
  id,
  slot,
  output,
  input,
  style
}: UpgradeParams<Data>): boolean {
  /**
   * @description v1.0.22 支持领域模型
   */

  if (typeof data.domainModel === 'undefined') {
    data.domainModel = {};
  }
  /**
   * @description v1.0.13 增加动态设置表头
   */

  if (typeof data.useDynamicTitle === 'undefined') {
    data.useDynamicTitle = false;
  }

  /**
   * style升级
   */
  data.columns.forEach((item, index) => {
    const { titleColor, titleBgColor, headStyle, contentStyle, contentColor } = item;
    const headSelector = `table thead tr th${getFilterSelector(id)}`;
    const bodySelector = `table tbody tr td${getFilterSelector(id)}`;

    if (titleColor || titleBgColor || !isEmptyObject(headStyle)) {
      setDeclaredStyle(headSelector, {
        color: titleColor,
        backgroundColor: titleBgColor,
        ...headStyle
      });
      item.titleColor = '';
      item.titleBgColor = '';
      item.headStyle = {};
    }

    if (contentColor || !isEmptyObject(contentStyle)) {
      setDeclaredStyle(bodySelector, {
        color: contentColor,
        ...contentStyle
      });
      item.contentColor = '';
      item.contentStyle = {};
    }
  });

  /*
   * 更新行数据 添加插槽列的新输出
   */
  const addOutput = (
    slotId: any,
    outputId: string,
    title = '更新行数据',
    schema?: Record<string, any>
  ) => {
    const slotItem = slot.get(slotId);
    if (slotItem && !slotItem.outputs.get(outputId)) {
      slotItem.outputs.add(
        outputId,
        title,
        schema || {
          type: 'object',
          properties: {
            index: {
              type: 'number'
            },
            value: {
              type: 'any'
            }
          }
        }
      );
    }
  };

  const UpdateColumnsOutput = (columns: IColumn[]) => {
    columns.forEach((column) => {
      if (column.contentType === ContentTypeEnum.SlotItem && slot?.get(column.slotId)) {
        addOutput(column.slotId, OutputIds.Edit_Table_Data);
        addOutput(column.slotId, OutputIds.Row_Move_Up, '上移行', Schemas.Number);
        addOutput(column.slotId, OutputIds.Row_Move_Down, '下移行', Schemas.Number);
        addOutput(column.slotId, OutputIds.Remove_Row, '移除行', Schemas.Number);
      }
      if (column.children) {
        UpdateColumnsOutput(column.children);
      }
    });
  };

  UpdateColumnsOutput(data.columns);
  // 列插槽作用域schema
  upgradeSchema({ data, output, input, slot });

  const useFilter = data.columns.some((item) => item.filter?.enable);
  if (useFilter) {
    output.add(OutputIds.FILTER_CLICK, '点击筛选', Schemas.Object);
  }

  if (!output.get(OutputIds.COLUMNS_CHANGE)) {
    output.add(OutputIds.COLUMNS_CHANGE, '列结构变化', Schemas.Array);
  }
  if (!output.get(OutputIds.CELL_CLICK)) {
    output.add(OutputIds.CELL_CLICK, '点击单元格', Schemas.CEll_CLICK);
  }

  addFilterIO({ data, output, input });

  if (data?.useSummaryColumn === undefined) {
    data.useSummaryColumn = false;
  }
  if (data?.summaryColumnTitle === undefined) {
    data.summaryColumnTitle = '合计';
  }
  if (data?.summaryCellTitleCol === undefined) {
    data.summaryCellTitleCol = 1;
  }
  if (data?.summaryColumnContentType === undefined) {
    data.summaryColumnContentType = 'text';
  }
  if (data?.summaryColumnContentSchema === undefined) {
    data.summaryColumnContentSchema = {
      type: 'string'
    };
  }

  /**
   * @description 1.0.68->1.0.69  更改target
   */
  const prePaginationStyle = getDeclaredStyle(
    `.ant-pagination.ant-pagination-disabled .ant-pagination-item-link`
  );

  let paginationCss: React.CSSProperties = {};

  if (prePaginationStyle) {
    paginationCss = { ...prePaginationStyle.css };
    removeDeclaredStyle(`.ant-pagination.ant-pagination-disabled .ant-pagination-item-link`);
    setDeclaredStyle('.ant-pagination-disabled > .ant-pagination-item-link', paginationCss);
  }

  /**
   * @description 1.0.73 “设置当前页码”增加 ”设置完成“ 关联输出项
   */

  const setPageNumPin = input.get(PaginatorInputIds.SetPageNum);
  const setPageNumFinishPin = output.get(PaginatorOutputIds.SetPageNumFinish);
  if (setPageNumPin) {
    if (!setPageNumFinishPin) {
      output.add(PaginatorOutputIds.SetPageNumFinish, '设置页码完成', {
        type: 'number'
      });
    }
    if (!setPageNumPin.rels) {
      setPageNumPin.setRels([PaginatorOutputIds.SetPageNumFinish]);
    }
  }

  //=========== v1.0.73 end ===============

  /**
   * @description v1.0.76 合并勾选项
   */
  if (data?.mergeCheckboxColumn === undefined) {
    data.mergeCheckboxColumn = false;
  }

  /**
   * @description v1.0.88->1.0.89 自定义空白文案和图片
   */
  if (data?.description === undefined) {
    data.description = '暂无数据';
  }
  // if(data?.isImage === undefined){
  //   data.isImage = false;
  // }
  // if (data?.image === undefined) {
  //   data.image =
  //     '';
  // }
  //=========== v1.0.89 end ===============

  /**
   * @description v1.0.89->1.0.90 fix&feat 增加自定空状态开关
   */
  if (data?.isEmpty === undefined) {
    data.isEmpty = false;
  }
  //=========== v1.0.90 end ===============

  if (data?.onRowScript === undefined) {
    data.onRowScript = DefaultOnRowScript;
  }
  //=========== v1.0.98 end ===============

  /**
   * @description v1.1.0->1.1.1 feat 新增对应串行输出
   */
  const setRels = (InputId: any, OutputId: any, OutputTitle: any, Schema: any = Schemas.Any) => {
    const Input = input.get(InputId);
    const OutPut = output.get(OutputId);
    if (Input) {
      if (!OutPut) {
        output.add(OutputId, OutputTitle, Schema);
      }
      if (!Input.rels) {
        Input.setRels([OutputId]);
      }
    }
  };
  setRels(InputIds.SET_DATA_SOURCE, OutputIds.SET_DATA_SOURCE, '数据源', Schemas.Array);
  setRels(InputIds.START_LOADING, OutputIds.START_LOADING, '开启loading后');
  setRels(InputIds.END_LOADING, OutputIds.END_LOADING, '关闭loading后');

  setRels(InputIds.CLEAR_ROW_SELECTION, OutputIds.CLEAR_ROW_SELECTION, '清空勾选后', Schemas.Void);
  setRels(InputIds.SET_FILTER, OutputIds.SET_FILTER, '筛选数据', Schemas.Object);
  setRels(InputIds.SET_SORT, OutputIds.SET_SORT, '排序数据', Schemas.SORTER);
  setRels(InputIds.TABLE_HEIGHT, OutputIds.TABLE_HEIGHT, '表格高度', Schemas.TABLE_HEIGHT);
  setRels(InputIds.SUMMARY_COLUMN, OutputIds.SUMMARY_COLUMN, '总结栏数据', Schemas.String);
  setRels(
    InputIds.SET_SHOW_COLUMNS,
    OutputIds.SET_SHOW_COLUMNS,
    '显示列',
    Schemas.SET_SHOW_COLUMNS
  );
  setRels(InputIds.SET_SHOW_TitleS, OutputIds.SET_SHOW_TitleS, '表头', Schemas.SET_SHOW_TitleS);
  setRels(
    InputIds.CHANGE_COLS_ATTR,
    OutputIds.CHANGE_COLS_ATTR,
    '列属性',
    Schemas.CHANGE_COLS_ATTR
  );
  setRels(
    InputIds.SET_ROW_SELECTION,
    OutputIds.SET_ROW_SELECTION,
    '勾选项',
    Schemas.SET_ROW_SELECTION
  );
  setRels(InputIds.SET_FILTER_INPUT, OutputIds.SET_FILTER_INPUT, '筛选项', Schemas.Object);
  setRels(
    InputIds.EnableAllExpandedRows,
    OutputIds.EnableAllExpandedRows,
    '开启关闭所有展开项',
    Schemas.Boolean
  );

  setRels(
    PaginatorInputIds.SetTotal,
    PaginatorOutputIds.SetTotal,
    '设置数据总数完成',
    Schemas.Number
  );
  setRels(PaginatorInputIds.SetDisable, PaginatorOutputIds.SetDisable, '禁用分页器后');
  setRels(PaginatorInputIds.SetEnable, PaginatorOutputIds.SetEnable, '启用分页器后');

  //=========== v1.1.1 end ===============

  /**
   * @description v1.1.13 -> 1.1.14 开启表格高度配置
   */
  if (style.height === void 0) {
    style.height = 'auto';
  }

  if (data?.enableRowFocus && !input.get(InputIds.SET_FOCUS_ROW)) {
    input.add(InputIds.SET_FOCUS_ROW, '设置选中行序号', Schemas.SET_FOCUS_ROW);
    output.add(OutputIds.SET_FOCUS_ROW, '设置选中行之后', Schemas.SET_FOCUS_ROW);
    input.get(InputIds.SET_FOCUS_ROW).setRels([OutputIds.SET_FOCUS_ROW]);
  }

  /**
   * @description v1.1.36 -> v1.1.37 新增动态设置布局风格能力
   */
  if (!input.get(InputIds.SET_SIZE)) {
    input.add(InputIds.SET_SIZE, '设置布局风格', Schemas.SET_SIZE);
    output.add(OutputIds.SET_SIZE_DONE, '设置布局风格完成', Schemas.SET_SIZE_DONE);
    input.get(InputIds.SET_SIZE).setRels([OutputIds.SET_SIZE_DONE]);
  }

  /**
   * @description v1.1.39 -> v1.1.40 筛选图标配置方式升级
   */
  if (!data.filterIconDefault || ['filter', 'search'].includes(data.filterIconDefault)) {
    if (data.filterIconDefault === 'search') data.filterIconDefault = 'SearchOutlined';
    else data.filterIconDefault = 'FilterFilled';
  }

  /**
   * @description v1.1.39 -> v1.1.40 筛选图标配置方式升级
   */
  data.columns.forEach((item, index) => {
    if (item.filter?.filterIcon === 'search') item.filter.filterIcon = 'SearchOutlined';
    else if (item.filter?.filterIcon === 'filter') item.filter.filterIcon = 'FilterFilled';
    else if (item.filter?.filterIcon === 'inherit') {
      item.filter.filterIcon = void 0;
      item.filter.filterIconInherit = true;
    }
    if (!item.filter?.filterIcon) {
      if (!item.filter) item.filter = { filterIconInherit: true };
      else item.filter.filterIconInherit = true;
    }
  });

  if (
    data.useRowSelection &&
    (data.selectionType === RowSelectionTypeEnum.Radio || !data.rowSelectionPostion?.length)
  ) {
    if (slot.get(SlotIds.ROW_SELECTION_OPERATION)) {
      slot.remove(SlotIds.ROW_SELECTION_OPERATION);
    }
  }

  return true;
}
